<template>
    <!-- 原有的表单元素 -->
    <el-form-item label="年级:" prop="level">
      <el-select 
        v-model="ruleForm.level" 
        style="width: 200px" 
        clearable 
        placeholder="请选择年级"
        @change="handleGradeChange"
        :loading="loading"
      >
        <el-option 
          v-for="item in levelStore.list"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
  
    <el-form-item label="学科:" prop="subject">
      <el-select 
        v-model="ruleForm.subject" 
        style="width: 200px" 
        clearable 
        placeholder="请选择学科"
        :disabled="!ruleForm.level"
        :loading="loading"
      >
        <el-option 
          v-for="subject in filteredSubjects"
          :key="subject.id"
          :label="subject.name"
          :value="subject.id"
        />
      </el-select>
    </el-form-item>
  
    <el-form-item label="题干:">
      <el-input v-model="questionTitle" placeholder="请输入题干" clearable style="width: 200px" @clear="" />
    </el-form-item>
  
    <el-form-item label="答案:">
      <el-input v-model="answer" placeholder="请输入答案" clearable style="width: 600px" @clear="" />
    </el-form-item>
  
    <el-form-item label="解析:">
      <el-input v-model="analysis" placeholder="请输入解析" clearable style="width: 600px" @clear="" />
    </el-form-item>
  
    <el-form-item label="分数:">
      <el-input-number v-model="num" :precision="1" :step="0.1" :max="10" />
    </el-form-item>
  
    <el-form-item label="难度:">
      <el-rate v-model="value" clearable />
    </el-form-item>
  
    <el-form-item>
      <el-button type="primary" @click="submitQuestion">提交</el-button>
      <el-button type="" @click="resetForm">重置</el-button>
      <el-button type="success" @click="openPreviewDialog">预览</el-button>
    </el-form-item>

    <!-- 预览组件 -->
    <Zujian ref="previewDialogRef">
      <template #content>
        <h4>答案:</h4>
        <div>{{ answer }}</div>
      </template>
    </Zujian>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useLevelStore } from '@/stores/level'
import { getSubjectList, type Subject, editQuestion, getQuestionDetail } from '@/api/juanti'
import Zujian from './Zujian.vue'
import { useRoute } from 'vue-router'

const levelStore = useLevelStore()
const loading = ref(false)
const subjectList = ref<Subject[]>([])
const filteredSubjects = ref<Subject[]>([])
const ruleForm = reactive({
  level: null as number | null,
  subject: null as number | null
})

const route = useRoute()

// 复用相同的加载和筛选逻辑
const loadSubjects = async () => {
  try {
    loading.value = true
    const response = await getSubjectList()
    if (response?.code === 1 && Array.isArray(response?.response)) {
      subjectList.value = response.response
      filterSubjects()
    }
  } catch (error) {
    console.error('加载学科列表失败:', error)
  } finally {
    loading.value = false
  }
}

const filterSubjects = () => {
  if (ruleForm.level) {
    filteredSubjects.value = subjectList.value
      .filter(item => item.level === ruleForm.level)
  } else {
    filteredSubjects.value = []
  }
}

const handleGradeChange = () => {
  filterSubjects()
  ruleForm.subject = null
}

// 加载题目数据
const loadQuestionData = async (id: number) => {
  try {
    const response = await getQuestionDetail(id)
    if (response.code === 1 && response.response) {
      const data = response.response
      
      ruleForm.level = data.gradeLevel
      ruleForm.subject = data.subjectId
      questionTitle.value = data.title
      answer.value = data.correct
      analysis.value = data.analyze
      num.value = parseFloat(data.score)
      value.value = data.difficult
    }
  } catch (error) {
    console.error('加载题目失败:', error)
  }
}

onMounted(() => {
  loadSubjects()
  
  // 如果是编辑模式，加载题目数据
  const questionId = route.query.id as string
  if (questionId) {
    loadQuestionData(parseInt(questionId))
  }
})

const num = ref(0)
const value = ref(3)
const questionTitle = ref('')
const answer = ref('')
const analysis = ref('')

const previewDialogRef = ref<InstanceType<typeof Zujian>>()

// 打开预览对话框
const openPreviewDialog = () => {
  if (previewDialogRef.value) {
    previewDialogRef.value.openDialog()
  } else {
    console.error('预览对话框引用未定义')
  }
}

const resetForm = () => {
  num.value = 0
  value.value = 3
  questionTitle.value = ''
  answer.value = ''
  analysis.value = ''
  ruleForm.level = null
  ruleForm.subject = null
}

// 提交题目
const submitQuestion = async () => {
  try {
    const params = {
      id: route.query.id ? parseInt(route.query.id as string) : 0,
      questionType: 5,
      subjectId: ruleForm.subject || 0,
      title: questionTitle.value,
      gradeLevel: ruleForm.level || 0,
      items: [],
      analyze: analysis.value,
      correctArray: null,
      correct: answer.value,
      score: num.value,
      difficult: value.value,
      itemOrder: null
    }
    const response = await editQuestion(params)
    if (response.code === 1) {
      console.log('提交成功')
    } else {
      console.error('提交失败:', response.message)
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}
</script>